package com.qk.management.web.interceptor;

import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @author: hm
 * @Date: 2025/10/11 15:37
 * @Description:
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class LoginCheckInterceptor implements HandlerInterceptor {

    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        Optional<String> requestURI = Optional.of(request.getRequestURI());
        if (!requestURI.isPresent()){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        Optional<String> token = Optional.of(request.getHeader(TOKEN_HEADER_NAME));
        if (!token.isPresent()){
            log.info("请求未携带token!");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        try {
            Claims claims = JwtUtils.parseToken(token.get());
            log.info("token验证成功!");
            String username = claims.get("username", String.class);
            log.info("请求用户名: {}", username);
            Integer id = claims.get("id",Integer.class);
            log.info("请求用户ID: {}", id);
            CurrentUserContextHolders.set(id);
            return true;
        } catch (Exception e) {
            log.error("token验证失败: {}", e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
